<!DOCTYPE html>
<html lang="en" color-mode="light">

  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="keywords" content="JavaScript,Hexo" />
  <meta name="author" content="超能虾米" />
  <meta name="description" content="" />
  
  
  <title>
    
      MongoDB整合到Spring Boot 
      
      
      |
    
     超能虾米的博客
  </title>

  
    <link rel="apple-touch-icon" href="/images/favicon.png">
    <link rel="icon" href="/images/favicon.png">
  

  <!-- Raleway-Font -->
  <link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">

  <!-- hexo site css -->
  <link rel="stylesheet" href="/css/main.css" />
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1886449_67xjft27j1l.css" />
  <!-- 代码块风格 -->
  

  <!-- jquery3.3.1 -->
  
    <script defer type="text/javascript" src="/plugins/jquery.min.js"></script>
  

  <!-- fancybox -->
  
    <link href="/plugins/jquery.fancybox.min.css" rel="stylesheet">
    <script defer type="text/javascript" src="/plugins/jquery.fancybox.min.js"></script>
  
  
<script src="/js/fancybox.js"></script>


  

  

  <script>
    var html = document.documentElement
    const colorMode = localStorage.getItem('color-mode')
    if (colorMode) {
      document.documentElement.setAttribute('color-mode', colorMode)
    }
  </script>
<meta name="generator" content="Hexo 5.4.2"><link rel="alternate" href="/atom.xml" title="超能虾米的博客" type="application/atom+xml">
</head>


  <body>
    <div id="app">
      <div class="header">
  <div class="avatar">
    <a href="/">
      <!-- 头像取消懒加载，添加no-lazy -->
      
        <img src="/images/头像.JPEG" alt="">
      
    </a>
    <div class="nickname"><a href="/">超能虾米</a></div>
  </div>
  <div class="navbar">
    <ul>
      
        <li class="nav-item" data-path="/">
          <a href="/">主页</a>
        </li>
      
        <li class="nav-item" data-path="/archives/">
          <a href="/archives/">归档</a>
        </li>
      
        <li class="nav-item" data-path="/categories/">
          <a href="/categories/">分类</a>
        </li>
      
        <li class="nav-item" data-path="/tags/">
          <a href="/tags/">标签</a>
        </li>
      
        <li class="nav-item" data-path="/friends/">
          <a href="/friends/">朋友</a>
        </li>
      
        <li class="nav-item" data-path="/about/">
          <a href="/about/">关于我</a>
        </li>
      
    </ul>
  </div>
</div>


<script src="/js/activeNav.js"></script>



      <div class="flex-container">
        <!-- 文章详情页，展示文章具体内容，url形式：https://yoursite/文章标题/ -->
<!-- 同时为「标签tag」，「朋友friend」，「分类categories」，「关于about」页面的承载页面，具体展示取决于page.type -->


  <!-- LaTex Display -->

  
    <script async type="text/javascript" src="/plugins/mathjax/tex-chtml.js"></script>
  
  <script>
    MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']]
      }
    }
  </script>





  <!-- clipboard -->

  
    <script async type="text/javascript" src="/plugins/clipboard.min.js"></script>
  
  
<script src="/js/codeCopy.js"></script>







  

  

  

  
  <!-- 文章内容页 url形式：https://yoursite/文章标题/ -->
  <div class="container post-details" id="post-details">
    <div class="post-content">
      <div class="post-title">MongoDB整合到Spring Boot</div>
      <div class="post-attach">
        <span class="post-pubtime">
          <i class="iconfont icon-updatetime mr-10" title="Update time"></i>
          2023-05-08 17:00:14
        </span>
        
              <span class="post-categories">
                <i class="iconfont icon-bookmark" title="Categories"></i>
                
                <span class="span--category">
                  <a href="/categories/%E5%90%8E%E7%AB%AF/" title="后端">
                    <b>#</b> 后端
                  </a>
                </span>
                
                <span class="span--category">
                  <a href="/categories/%E5%90%8E%E7%AB%AF/%E4%B8%AD%E9%97%B4%E4%BB%B6/" title="中间件">
                    <b>#</b> 中间件
                  </a>
                </span>
                
              </span>
          
              <span class="post-tags">
                <i class="iconfont icon-tags mr-10" title="Tags"></i>
                
                <span class="span--tag mr-8">
                  <a href="/tags/Java/" title="Java">
                    #Java
                  </a>
                </span>
                
              </span>
          
      </div>
      <div class="markdown-body">
        <h3 id="1-本机测试，使用-Docker-快速搭建-MongoDB："><a href="#1-本机测试，使用-Docker-快速搭建-MongoDB：" class="headerlink" title="1. 本机测试，使用 Docker 快速搭建 MongoDB："></a>1. 本机测试，使用 Docker 快速搭建 MongoDB：</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">docker run -itd --name mongo -p 27017:27017 mongo --auth</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">$ </span><span class="language-bash">docker <span class="built_in">exec</span> -it mongo mongo admin</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">创建一个名为 admin，密码为 123456 的用户。</span></span><br><span class="line"><span class="meta prompt_">&gt; </span><span class="language-bash"> db.createUser(&#123; user:<span class="string">&#x27;admin&#x27;</span>,<span class="built_in">pwd</span>:<span class="string">&#x27;123456&#x27;</span>,roles:[ &#123; role:<span class="string">&#x27;userAdminAnyDatabase&#x27;</span>, db: <span class="string">&#x27;admin&#x27;</span>&#125;,<span class="string">&quot;readWriteAnyDatabase&quot;</span>]&#125;);</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">尝试使用上面创建的用户信息进行连接，验证成功返回1。</span></span><br><span class="line"><span class="meta prompt_">&gt; </span><span class="language-bash">db.auth(<span class="string">&#x27;admin&#x27;</span>, <span class="string">&#x27;123456&#x27;</span>)</span></span><br></pre></td></tr></table></figure>
<h3 id="2-Spring-Boot-导入-mongodb-相关依赖"><a href="#2-Spring-Boot-导入-mongodb-相关依赖" class="headerlink" title="2. Spring Boot 导入 mongodb 相关依赖"></a>2. Spring Boot 导入 mongodb 相关依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>  </span><br><span class="line">	<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>  </span><br><span class="line">	<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-mongodb<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span>  </span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="3-编辑-Spring-Boot-配置文件"><a href="#3-编辑-Spring-Boot-配置文件" class="headerlink" title="3. 编辑 Spring Boot 配置文件"></a>3. 编辑 Spring Boot 配置文件</h3><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span>  </span><br><span class="line">	<span class="attr">data:</span>  </span><br><span class="line">		<span class="attr">mongodb:</span>  </span><br><span class="line">			<span class="attr">uri:</span> <span class="string">mongodb://admin:123456@localhost:27017/admin</span></span><br></pre></td></tr></table></figure>
<h3 id="4-基于MongoTemplate-开发CRUD"><a href="#4-基于MongoTemplate-开发CRUD" class="headerlink" title="4. 基于MongoTemplate 开发CRUD"></a>4. 基于MongoTemplate 开发CRUD</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootTest</span>  </span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ApplicationTests</span> &#123;  </span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">insert</span><span class="params">()</span> &#123;  </span><br><span class="line">		<span class="type">User</span> <span class="variable">alice</span> <span class="operator">=</span> mongoTemplate.insert(<span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;1&quot;</span>, <span class="string">&quot;Alice&quot;</span>, <span class="number">23</span>));  </span><br><span class="line">		System.out.println(alice);  </span><br><span class="line">	&#125;  </span><br><span class="line">	  </span><br><span class="line">	<span class="comment">// 查询全部  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">findAll</span><span class="params">()</span> &#123;  </span><br><span class="line">		List&lt;User&gt; all = mongoTemplate.findAll(User.class);  </span><br><span class="line">		all.forEach(System.out::println);  </span><br><span class="line">	&#125;  </span><br><span class="line">	  </span><br><span class="line">	<span class="comment">// 根据id查询  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">findById</span><span class="params">()</span> &#123;  </span><br><span class="line">		<span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> mongoTemplate.findById(<span class="string">&quot;1&quot;</span>, User.class);  </span><br><span class="line">		System.out.println(user);  </span><br><span class="line">	&#125;  </span><br><span class="line">	  </span><br><span class="line">	<span class="comment">// 根据条件查询  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">findByName</span><span class="params">()</span> &#123;  </span><br><span class="line">		<span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> Query.query(Criteria.where(<span class="string">&quot;name&quot;</span>).is(<span class="string">&quot;Alice&quot;</span>));  </span><br><span class="line">		List&lt;User&gt; users = mongoTemplate.find(query, User.class);  </span><br><span class="line">		users.forEach(System.out::println);  </span><br><span class="line">	&#125;  </span><br><span class="line">	  </span><br><span class="line">	<span class="comment">// 模糊查询  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">findByNameLike</span><span class="params">()</span> &#123;  </span><br><span class="line">		<span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> Query.query(Criteria.where(<span class="string">&quot;name&quot;</span>).regex(<span class="string">&quot;A&quot;</span>));  </span><br><span class="line">		List&lt;User&gt; users = mongoTemplate.find(query, User.class);  </span><br><span class="line">		users.forEach(System.out::println);  </span><br><span class="line">	&#125;  </span><br><span class="line">	  </span><br><span class="line">	<span class="comment">// 分页查询  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">findByNameLikePage</span><span class="params">()</span> &#123;  </span><br><span class="line">		<span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> Query.query(Criteria.where(<span class="string">&quot;name&quot;</span>).regex(<span class="string">&quot;A&quot;</span>));  </span><br><span class="line">		query.skip(<span class="number">0</span>).limit(<span class="number">2</span>);  </span><br><span class="line">		List&lt;User&gt; users = mongoTemplate.find(query, User.class);  </span><br><span class="line">		users.forEach(System.out::println);  </span><br><span class="line">	&#125;  </span><br><span class="line">	  </span><br><span class="line">	<span class="comment">// 修改  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">update1</span><span class="params">()</span> &#123;  </span><br><span class="line">		<span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> Query.query(Criteria.where(<span class="string">&quot;name&quot;</span>).is(<span class="string">&quot;Alice&quot;</span>));  </span><br><span class="line">		<span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> mongoTemplate.findOne(query, User.class);  </span><br><span class="line">		user.setAge(<span class="number">24</span>);  </span><br><span class="line">		mongoTemplate.save(user);  </span><br><span class="line">	&#125;  </span><br><span class="line">	  </span><br><span class="line">	<span class="comment">// 修改  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">update2</span><span class="params">()</span> &#123;  </span><br><span class="line">		<span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> Query.query(Criteria.where(<span class="string">&quot;name&quot;</span>).is(<span class="string">&quot;Alice&quot;</span>));  </span><br><span class="line">		<span class="type">Update</span> <span class="variable">update</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Update</span>();  </span><br><span class="line">		update.set(<span class="string">&quot;age&quot;</span>, <span class="number">25</span>);  </span><br><span class="line">		<span class="type">UpdateResult</span> <span class="variable">upsert</span> <span class="operator">=</span> mongoTemplate.upsert(query, update, User.class);  </span><br><span class="line">		<span class="type">long</span> <span class="variable">modifiedCount</span> <span class="operator">=</span> upsert.getModifiedCount();<span class="comment">//获取到修改受影响的行数  </span></span><br><span class="line">		System.out.println(<span class="string">&quot;受影响的条数：&quot;</span>+modifiedCount);  </span><br><span class="line">	&#125;  </span><br><span class="line">	  </span><br><span class="line">	<span class="comment">// 删除  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">void</span> <span class="title function_">delete</span><span class="params">()</span> &#123;  </span><br><span class="line">		<span class="type">Query</span> <span class="variable">query</span> <span class="operator">=</span> Query.query(Criteria.where(<span class="string">&quot;name&quot;</span>).is(<span class="string">&quot;Alice&quot;</span>));  </span><br><span class="line">		<span class="type">DeleteResult</span> <span class="variable">remove</span> <span class="operator">=</span> mongoTemplate.remove(query, User.class);  </span><br><span class="line">		<span class="type">long</span> <span class="variable">deletedCount</span> <span class="operator">=</span> remove.getDeletedCount();  </span><br><span class="line">		System.out.println(<span class="string">&quot;删除的条数：&quot;</span>+deletedCount);  </span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="5-基于-MongoRepository-开发-CRUD"><a href="#5-基于-MongoRepository-开发-CRUD" class="headerlink" title="5. 基于 MongoRepository 开发 CRUD"></a>5. 基于 MongoRepository 开发 CRUD</h3><p>Spring Data 提供了对 mongodb 数据访问的支持，我们只需要继承 MongoRepository 类，按照 Spring Data 规范就可以了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootTest</span>  </span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ApplicationTests</span> &#123;  </span><br><span class="line">	<span class="meta">@Autowired</span>  </span><br><span class="line">	<span class="keyword">private</span> UserRepository userRepository;  </span><br><span class="line">	<span class="comment">// 保存  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">save</span><span class="params">()</span>&#123;  </span><br><span class="line">		<span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> userRepository.save(<span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;2&quot;</span>, <span class="string">&quot;Demon&quot;</span>, <span class="number">21</span>));  </span><br><span class="line">		System.out.println(user1);  </span><br><span class="line">	&#125;  </span><br><span class="line">	<span class="comment">//查询所有  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">findAll</span><span class="params">()</span>&#123;  </span><br><span class="line">		List&lt;User&gt; lists = userRepository.findAll();  </span><br><span class="line">		lists.forEach(System.out::println); </span><br><span class="line">	&#125;  </span><br><span class="line">	<span class="comment">//根据id查询  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">findById</span><span class="params">()</span>&#123;  </span><br><span class="line">		<span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> userRepository.findById(<span class="string">&quot;2&quot;</span>).get();  </span><br><span class="line">		System.out.println(user);  </span><br><span class="line">	&#125;  </span><br><span class="line">	  </span><br><span class="line">	<span class="comment">//条件查询  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">findUserList</span><span class="params">()</span>&#123;  </span><br><span class="line">		<span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();  </span><br><span class="line">		user.setName(<span class="string">&quot;Demon&quot;</span>);  </span><br><span class="line">		user.setAge(<span class="number">21</span>);  </span><br><span class="line">		Example&lt;User&gt; example = Example.of(user);  </span><br><span class="line">		List&lt;User&gt; all = userRepository.findAll(example);  </span><br><span class="line">		System.out.println(all);  </span><br><span class="line">	&#125;  </span><br><span class="line">	<span class="comment">//模糊条件查询  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">findLikeUserList</span><span class="params">()</span>&#123;  </span><br><span class="line">		<span class="comment">///创建匹配器，即如何使用查询条件  </span></span><br><span class="line">		<span class="type">ExampleMatcher</span> <span class="variable">matcher</span> <span class="operator">=</span> ExampleMatcher.matching()<span class="comment">//构建对象  </span></span><br><span class="line">		.withStringMatcher(ExampleMatcher.StringMatcher.STARTING)<span class="comment">//改变默认字符串匹配方式：模糊查询  </span></span><br><span class="line">		.withIgnoreCase(<span class="literal">true</span>);<span class="comment">//改变默认大小写忽略方式：忽略大小写  </span></span><br><span class="line">		  </span><br><span class="line">		<span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();  </span><br><span class="line">		user.setName(<span class="string">&quot;De&quot;</span>);  </span><br><span class="line">		user.setAge(<span class="number">21</span>);  </span><br><span class="line">		Example&lt;User&gt; example = Example.of(user, matcher);  </span><br><span class="line">		List&lt;User&gt; all = userRepository.findAll(example);  </span><br><span class="line">		System.out.println(all);  </span><br><span class="line">	&#125;  </span><br><span class="line">	<span class="comment">//分页查询  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">findPageUserAll</span><span class="params">()</span>&#123;  </span><br><span class="line">		<span class="comment">//设置分页参数  </span></span><br><span class="line">		<span class="comment">//0代表第一页  </span></span><br><span class="line">		<span class="type">Pageable</span> <span class="variable">pageable</span> <span class="operator">=</span> PageRequest.of(<span class="number">0</span>, <span class="number">3</span>);  </span><br><span class="line">		<span class="comment">//查询条件  </span></span><br><span class="line">		<span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();  </span><br><span class="line">		user.setName(<span class="string">&quot;Demon&quot;</span>);  </span><br><span class="line">		user.setAge(<span class="number">21</span>);  </span><br><span class="line">		Example&lt;User&gt; userExample = Example.of(user);<span class="comment">//查询条件  </span></span><br><span class="line">		Page&lt;User&gt; page = userRepository.findAll(userExample, pageable);  </span><br><span class="line">		System.out.println(page.getContent());  </span><br><span class="line">	&#125;  </span><br><span class="line">	<span class="comment">//修改操作  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">updateUser</span><span class="params">()</span>&#123;  </span><br><span class="line">		<span class="comment">//先根据id出要修改的用户  </span></span><br><span class="line">		<span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> userRepository.findById(<span class="string">&quot;2&quot;</span>).get();  </span><br><span class="line">		<span class="comment">//设置修改的值  </span></span><br><span class="line">		user.setAge(<span class="number">24</span>);  </span><br><span class="line">		<span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span> userRepository.save(user);  </span><br><span class="line">		System.out.println(user1);  </span><br><span class="line">	&#125;  </span><br><span class="line">	<span class="comment">//删除  </span></span><br><span class="line">	<span class="meta">@Test</span>  </span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">delete</span><span class="params">()</span>&#123;  </span><br><span class="line">		userRepository.deleteById(<span class="string">&quot;2&quot;</span>);  </span><br><span class="line">	&#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


      </div>
      
        <div class="prev-or-next">
          <div class="post-foot-next">
            
              <a href="/2023/05/08/%E5%90%8E%E7%AB%AF/Spring/@Configuration%E5%92%8C@Component%20%E5%8C%BA%E5%88%AB/" target="_self">
                <i class="iconfont icon-chevronleft"></i>
                <span>Prev</span>
              </a>
            
          </div>
          <div class="post-attach">
            <span class="post-pubtime">
              <i class="iconfont icon-updatetime mr-10" title="Update time"></i>
              2023-05-08 17:00:14
            </span>
            
                  <span class="post-categories">
                    <i class="iconfont icon-bookmark" title="Categories"></i>
                    
                    <span class="span--category">
                      <a href="/categories/%E5%90%8E%E7%AB%AF/" title="后端">
                        <b>#</b> 后端
                      </a>
                    </span>
                    
                    <span class="span--category">
                      <a href="/categories/%E5%90%8E%E7%AB%AF/%E4%B8%AD%E9%97%B4%E4%BB%B6/" title="中间件">
                        <b>#</b> 中间件
                      </a>
                    </span>
                    
                  </span>
              
                  <span class="post-tags">
                    <i class="iconfont icon-tags mr-10" title="Tags"></i>
                    
                    <span class="span--tag mr-8">
                      <a href="/tags/Java/" title="Java">
                        #Java
                      </a>
                    </span>
                    
                  </span>
              
          </div>
          <div class="post-foot-prev">
            
              <a href="/2023/05/08/%E5%90%8E%E7%AB%AF/Spring%20Boot/Spring%20Boot%20%E5%A6%82%E4%BD%95%E6%8F%90%E9%AB%98%E6%8E%A5%E5%8F%A3%E6%95%B0%E6%8D%AE%E5%AE%89%E5%85%A8%E6%80%A7/" target="_self">
                <span>Next</span>
                <i class="iconfont icon-chevronright"></i>
              </a>
            
          </div>
        </div>
      
    </div>
    
  <div id="btn-catalog" class="btn-catalog">
    <i class="iconfont icon-catalog"></i>
  </div>
  <div class="post-catalog hidden" id="catalog">
    <div class="title">Contents</div>
    <div class="catalog-content">
      
        <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E6%9C%AC%E6%9C%BA%E6%B5%8B%E8%AF%95%EF%BC%8C%E4%BD%BF%E7%94%A8-Docker-%E5%BF%AB%E9%80%9F%E6%90%AD%E5%BB%BA-MongoDB%EF%BC%9A"><span class="toc-text">1. 本机测试，使用 Docker 快速搭建 MongoDB：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-Spring-Boot-%E5%AF%BC%E5%85%A5-mongodb-%E7%9B%B8%E5%85%B3%E4%BE%9D%E8%B5%96"><span class="toc-text">2. Spring Boot 导入 mongodb 相关依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E7%BC%96%E8%BE%91-Spring-Boot-%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-text">3. 编辑 Spring Boot 配置文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E5%9F%BA%E4%BA%8EMongoTemplate-%E5%BC%80%E5%8F%91CRUD"><span class="toc-text">4. 基于MongoTemplate 开发CRUD</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E5%9F%BA%E4%BA%8E-MongoRepository-%E5%BC%80%E5%8F%91-CRUD"><span class="toc-text">5. 基于 MongoRepository 开发 CRUD</span></a></li></ol>
      
    </div>
  </div>

  
<script src="/js/catalog.js"></script>




    
      <div class="comments-container">
        




  
    <script async type="text/javascript" src="/plugins/valine.min.js" onload="loadValineSuc(this)"></script>
  

  <div id="vcomments"></div>

  <script>
    function loadValineSuc() {
      new Valine({
        el: '#vcomments',
        appId: 'H2QqshKF8elT2Si5bfKynT9h-9Nh9j0Va',
        appKey: 'WgtVppOWkTZ8fWNReNI1Ymf7',
        placeholder: '有问题请留言吧!',
        avatar: 'retro',
        lang: 'en'
      })
    }
  </script>

    <style>
      .comments-container .v .vempty {
        display: none!important;
      }
    </style>




      </div>
    
  </div>


        
<div class="footer">
  <div class="social">
    <ul>
      
        <li>
          <a title="github" target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">
            <i class="iconfont icon-github"></i>
          </a>
        </li>
      
        <li>
          <a title="email" target="_blank" rel="noopener" href="https://c77544s.github.io/about/">
            <i class="iconfont icon-envelope"></i>
          </a>
        </li>
      
        <li>
          <a title="wechat" target="_blank" rel="noopener" href="https://c77544s.github.io/about/">
            <i class="iconfont icon-wechat"></i>
          </a>
        </li>
      
        <li>
          <a title="rss" href="/atom.xml">
            <i class="iconfont icon-rss"></i>
          </a>
        </li>
      
    </ul>
  </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">Copyright © 2023 Oranges</a>
        
    </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">Theme by Oranges | Powered by Hexo</a>
        
    </div>
  
  
</div>

      </div>

      <div class="tools-bar">
        <div class="back-to-top tools-bar-item hidden">
  <a href="javascript: void(0)">
    <i class="iconfont icon-chevronup"></i>
  </a>
</div>


<script src="/js/backtotop.js"></script>



        
  <div class="search-icon tools-bar-item" id="search-icon">
    <a href="javascript: void(0)">
      <i class="iconfont icon-search"></i>
    </a>
  </div>

  <div class="search-overlay hidden">
    <div class="search-content" tabindex="0">
      <div class="search-title">
        <span class="search-icon-input">
          <a href="javascript: void(0)">
            <i class="iconfont icon-search"></i>
          </a>
        </span>
        
          <input type="text" class="search-input" id="search-input" placeholder="搜索...">
        
        <span class="search-close-icon" id="search-close-icon">
          <a href="javascript: void(0)">
            <i class="iconfont icon-close"></i>
          </a>
        </span>
      </div>
      <div class="search-result" id="search-result"></div>
    </div>
  </div>

  <script type="text/javascript">
    var inputArea = document.querySelector("#search-input")
    var searchOverlayArea = document.querySelector(".search-overlay")

    inputArea.onclick = function() {
      getSearchFile()
      this.onclick = null
    }

    inputArea.onkeydown = function() {
      if(event.keyCode == 13)
        return false
    }

    function openOrHideSearchContent() {
      let isHidden = searchOverlayArea.classList.contains('hidden')
      if (isHidden) {
        searchOverlayArea.classList.remove('hidden')
        document.body.classList.add('hidden')
        // inputArea.focus()
      } else {
        searchOverlayArea.classList.add('hidden')
        document.body.classList.remove('hidden')
      }
    }

    function blurSearchContent(e) {
      if (e.target === searchOverlayArea) {
        openOrHideSearchContent()
      }
    }

    document.querySelector("#search-icon").addEventListener("click", openOrHideSearchContent, false)
    document.querySelector("#search-close-icon").addEventListener("click", openOrHideSearchContent, false)
    searchOverlayArea.addEventListener("click", blurSearchContent, false)

    var searchFunc = function (path, search_id, content_id) {
      'use strict';
      var $input = document.getElementById(search_id);
      var $resultContent = document.getElementById(content_id);
      $resultContent.innerHTML = "<ul><span class='local-search-empty'>First search, index file loading, please wait...<span></ul>";
      $.ajax({
        // 0x01. load xml file
        url: path,
        dataType: "xml",
        success: function (xmlResponse) {
          // 0x02. parse xml file
          var datas = $("entry", xmlResponse).map(function () {
            return {
              title: $("title", this).text(),
              content: $("content", this).text(),
              url: $("url", this).text()
            };
          }).get();
          $resultContent.innerHTML = "";

          $input.addEventListener('input', function () {
            // 0x03. parse query to keywords list
            var str = '<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length <= 0) {
              return;
            }
            // 0x04. perform local searching
            datas.forEach(function (data) {
              var isMatch = true;
              var content_index = [];
              if (!data.title || data.title.trim() === '') {
                data.title = "Untitled";
              }
              var orig_data_title = data.title.trim();
              var data_title = orig_data_title.toLowerCase();
              var orig_data_content = data.content.trim().replace(/<[^>]+>/g, "");
              var data_content = orig_data_content.toLowerCase();
              var data_url = data.url;
              var index_title = -1;
              var index_content = -1;
              var first_occur = -1;
              // only match artiles with not empty contents
              if (data_content !== '') {
                keywords.forEach(function (keyword, i) {
                  index_title = data_title.indexOf(keyword);
                  index_content = data_content.indexOf(keyword);

                  if (index_title < 0 && index_content < 0) {
                    isMatch = false;
                  } else {
                    if (index_content < 0) {
                      index_content = 0;
                    }
                    if (i == 0) {
                      first_occur = index_content;
                    }
                    // content_index.push({index_content:index_content, keyword_len:keyword_len});
                  }
                });
              } else {
                isMatch = false;
              }
              // 0x05. show search results
              if (isMatch) {
                str += "<li><a href='" + data_url + "' class='search-result-title'>" + orig_data_title + "</a>";
                var content = orig_data_content;
                if (first_occur >= 0) {
                  // cut out 100 characters
                  var start = first_occur - 20;
                  var end = first_occur + 80;

                  if (start < 0) {
                    start = 0;
                  }

                  if (start == 0) {
                    end = 100;
                  }

                  if (end > content.length) {
                    end = content.length;
                  }

                  var match_content = content.substr(start, end);

                  // highlight all keywords
                  keywords.forEach(function (keyword) {
                    var regS = new RegExp(keyword, "gi");
                    match_content = match_content.replace(regS, "<span class=\"search-keyword\">" + keyword + "</span>");
                  });

                  str += "<p class=\"search-result-abstract\">" + match_content + "...</p>"
                }
                str += "</li>";
              }
            });
            str += "</ul>";
            if (str.indexOf('<li>') === -1) {
              return $resultContent.innerHTML = "<ul><span class='local-search-empty'>No result<span></ul>";
            }
            $resultContent.innerHTML = str;
          });
        },
        error: function(xhr, status, error) {
          $resultContent.innerHTML = ""
          if (xhr.status === 404) {
            $resultContent.innerHTML = "<ul><span class='local-search-empty'>The search.xml file was not found, please refer to：<a href='https://github.com/zchengsite/hexo-theme-oranges#configuration' target='_black'>configuration</a><span></ul>";
          } else {
            $resultContent.innerHTML = "<ul><span class='local-search-empty'>The request failed, Try to refresh the page or try again later.<span></ul>";
          }
        }
      });
      $(document).on('click', '#search-close-icon', function() {
        $('#search-input').val('');
        $('#search-result').html('');
      });
    }

    var getSearchFile = function() {
        var path = "/search.xml";
        searchFunc(path, 'search-input', 'search-result');
    }
  </script>




        
  <div class="tools-bar-item theme-icon" id="switch-color-scheme">
    <a href="javascript: void(0)">
      <i id="theme-icon" class="iconfont icon-moon"></i>
    </a>
  </div>

  
<script src="/js/colorscheme.js"></script>





        
  
    <div class="share-icon tools-bar-item">
      <a href="javascript: void(0)" id="share-icon">
        <i class="iconfont iconshare"></i>
      </a>
      <div class="share-content hidden">
        
          <a class="share-item" href="https://twitter.com/intent/tweet?text=' + MongoDB%E6%95%B4%E5%90%88%E5%88%B0Spring%20Boot + '&url=' + http%3A%2F%2Fc77544s.gitee.io%2F2023%2F05%2F08%2F%25E5%2590%258E%25E7%25AB%25AF%2F%25E4%25B8%25AD%25E9%2597%25B4%25E4%25BB%25B6%2FMongoDB%25E6%2595%25B4%25E5%2590%2588%25E5%2588%25B0Spring%2520Boot%2F + '" target="_blank" title="Twitter">
            <i class="iconfont icon-twitter"></i>
          </a>
        
        
          <a class="share-item" href="https://www.facebook.com/sharer.php?u=http://c77544s.gitee.io/2023/05/08/%E5%90%8E%E7%AB%AF/%E4%B8%AD%E9%97%B4%E4%BB%B6/MongoDB%E6%95%B4%E5%90%88%E5%88%B0Spring%20Boot/" target="_blank" title="Facebook">
            <i class="iconfont icon-facebooksquare"></i>
          </a>
        
      </div>
    </div>
  
  
<script src="/js/shares.js"></script>



      </div>
    </div>
  </body>
</html>
